package com.example.androidhuachipa;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class BuscarActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buscar);
        
        Button btnBuscar = (Button) findViewById(R.id.btnBuscar);
		final EditText txtAnimales = (EditText) findViewById(R.id.txtanimal);
		final TableLayout tlAnimales = (TableLayout) findViewById(R.id.tlProductos);

		btnBuscar.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				String texto = txtAnimales.getText().toString();
				RestClient cliente = new RestClient("http://192.168.1.36:8080/huachipa/rest/animales");
				cliente.AddParam("nombre", texto);

				try {
					cliente.Execute(RequestMethod.GET);					
					
					String jsontext = cliente.getResponse();
					
		            JSONArray entries = new JSONArray(jsontext);

		            String x = "";

		            tlAnimales.removeAllViews();
		            
		            int i;
		            for (i=0;i<entries.length();i++) {
		            	
		                JSONObject post = entries.getJSONObject(i);
		                x += "Nombre:" + post.getString("nombre") + "\n";
		                TableRow tr = new TableRow(getBaseContext());
		                
		                TextView valueTV = new TextView(getBaseContext());
		                valueTV.setText(post.getString("nombre"));
		                tr.addView(valueTV);
		                
		                tlAnimales.addView(tr);
		                
		            }
		            
					Log.i("BuscarActivity", x);
				} catch (Exception e) {
					Log.i("BuscarActivity", ":" + e.getMessage());
				}

			}
		});
	}

}
